package io.gitee.jingtuo.android.device.ui.splash

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.huawei.agconnect.auth.AGConnectAuth
import com.huawei.hmf.tasks.OnCompleteListener
import io.gitee.jingtuo.android.device.SysProManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class SplashViewModel : ViewModel() {

    private val uiState = MutableStateFlow(SplashUiState())

    fun uiState(): StateFlow<SplashUiState> {
        return uiState.asStateFlow()
    }

    fun init(context: Context) {
        viewModelScope.launch {
            val result = SysProManager.initProperties()
            val user = AGConnectAuth.getInstance().currentUser
            if (user == null) {
                //1363805644808814464
                AGConnectAuth.getInstance().signInAnonymously()
                    .addOnCompleteListener(OnCompleteListener {
                        uiState.update {
                            it.copy(initializing = false)
                        }
                    })
            } else {
                uiState.update {
                    it.copy(initializing = false)
                }
            }

        }
    }
}